package com.my.handler;

import com.my.config.GlobalConfig;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.AttributeKey;

/**
 * @author WangLuoXin
 * &#064;Date 2024/9/29  10:25
 * 初始化 消息处理组件
 **/
public class InitHandler extends ChannelInitializer<SocketChannel> {

    private final GlobalConfig globalConfig;

    public InitHandler(GlobalConfig globalConfig) {
        this.globalConfig = globalConfig;
    }

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast("httpAggregator", new HttpObjectAggregator(512 * 1024));
        //开始websocket支持
        if (globalConfig.getWebSocket().getOpen()) {
            //升级web socket前获取 http前置参数
            pipeline.addLast(new ChannelInboundHandlerAdapter() {
                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    if (msg instanceof HttpRequest) {
                        HttpRequest httpRequest = (HttpRequest) msg;
                        HttpHeaders headers = httpRequest.headers();
                        String upgrade = headers.get("Upgrade");
                        //处理升级请求
                        if (upgrade != null && upgrade.equalsIgnoreCase("websocket")) {
//                            headers.forEach(header -> System.out.println(header.getKey() + ": " + header.getValue()));
                            //传递下一层 自定义逻辑获取
                            headers.forEach(header -> ctx.channel()
                                    .attr(AttributeKey.valueOf(header.getKey()))
                                    .set(header.getValue()));
                        }
                    }
                    ctx.fireChannelRead(msg);
                }
            });
            pipeline.addLast(new WebSocketServerProtocolHandler(globalConfig.getWebSocket().getUrl()));
            pipeline.addLast(new WebSocketFrameHandler());
        }
        pipeline.addLast(new PreProcessorsHandler());
        pipeline.addLast(new HttpRequestHandler());

    }
}
